package com.arm.service.impl;

import com.arm.dao.UserMapper;
import com.arm.module.User;
import com.arm.service.BaseService;
import com.arm.service.UserService;
import com.arm.tools.MD5Tools;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017-11-21.
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
    @Autowired
    UserMapper userMapper;

    private static final String DEFOULT_PASSWORD = "123456";

    @Override
    public User getUserById(Long userId) {
        return null;
    }

    private void insertUser(User user) {
        userMapper.insertUser(user);
    }

    private void updateUser(User user) {
        userMapper.updateUserByPrimaryKeySelective(user);
    }

    @Override
    public User getUserByPhone(String phone) {
        return userMapper.getUser(new HashMap<String, String>() {
            {
                put("phone", phone);
            }
        });
    }

    @Override
    public User bindUser(String openId) {
        if (StringUtils.isBlank(openId)) {
            throw new MyRunTimeExcption("openId 不存在！");
        }

        User user = userMapper.getUser(new HashMap<String, String>() {
            {
                put("openId", openId);
            }
        });

        if (user == null) {
            user = new User();
            user.setUserType(User.USER_TYPE_NORMAL);
            user.setPassWord(MD5Tools.MD5(DEFOULT_PASSWORD));
            user.setOpenId(openId);
            user.setStatus(User.STATUS_VALID);
            user.setCreateTime(new Date());
            insertUser(user);
        }

        return user;
    }

    @Override
    public void modifyUser(User user) {
        if (user.getTid() == null) {
            user.setCreateTime(new Date());
            insertUser(user);
            return;
        }
        updateUser(user);
    }

    @Override
    public List<User> getUserList(Map<String, String> map) {
        return userMapper.getUserList(map);
    }
}
